<?php
/**
 * Created by JetBrains PhpStorm.
 * User: GMC
 * Date: 10/3/13
 * Time: 2:20 PM
 * To change this template use File | Settings | File Templates.
 */

class WidgetWideCategories extends CWidget {
    public $categories, $id, $child_ids;

    public function init() {
        $categories_cache = Yii::app()->cache->get('categories_cache');
        $categories_session = Yii::app()->session['categories_cache'];
        if ($categories_cache == null || count($categories_cache) == 0 || (isset($categories_session) && $categories_session)) {
            $categories = Category::model()->findAll(
                array(
                    'select' => 'cat_id,cat_name,products',
                    'condition' => 'parent_id = 0',
                    'order' => 't.order ASC'
                ));

            $parents = array();
            //get sub categories
            foreach ($categories as $category) {
                $content = '';
                $sub_categories = Category::model()->findAll(array(
                    'select' => 'cat_id,cat_name,products',
                    'condition' => 'parent_id = :id',
                    'params' => array(':id' => $category->cat_id)
                ));
                foreach ($sub_categories as $item) {
                    $content .= "<a href=" . TreTodayUrl::getCategoryUrl($item->cat_id, $item->cat_name) . ">» $item->cat_name ($item->products)</a>";
                }
                array_push($parents, array('parent' => $category->cat_name, 'sub' => $content));
            }

            Yii::app()->cache->set('categories_cache', $parents, Yii::app()->params['categories_cache_time']);
        }


        $this->categories = Yii::app()->cache->get('categories_cache');
    }

    public function run() {
        return CWidget::render('widgetWideCategories', array('results' => $this->categories));
    }
}